#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <poll.h>
#include "Socket.hpp"

using namespace socket_ns;

class PollServer
{
    const static int N = sizeof(fd_set) * 8;
    const static int defaultfd = -1;
    const static int defaultevent = 0;
    const static int gnum = 1024;

public:
    PollServer(uint16_t port)
        : _port(port),
          _listensock(std::make_unique<TcpSocket>())
    {
        InetAddr addr("0", port);
        _listensock->BuildListenSocket(addr);
        for (int i = 0; i < gnum; i++)
        {
            _events[i].fd = defaultfd;
            _events[i].events = defaultevent;
        }
        _events[0].fd = _listensock->SockFd();
        _events[0].events = POLLIN;
    }

    void AcceptClient()
    {
        // 只关心了读，而读fd分为：listensock 和 nornam sockfd
        InetAddr clientaddr;
        int sockfd = _listensock->Accepter(&clientaddr)->SockFd();
        if (sockfd < 0)
            return;

        LOG(DEBUG, "Get new link, sockfd: %d, client info %s:%d\n", sockfd, clientaddr.Ip().c_str(), clientaddr.Port());

        int pos = 1;
        for (; pos < N; pos++)
        {
            if (_events[pos].fd == defaultfd)
                break;
        }
        if (pos == N)
        {
            ::close(sockfd);
            LOG(WARRING, "server is full!\n");
            // 扩容
            return;
        }
        else
        {
            _events[pos].fd = sockfd;
            _events[pos].events = POLLIN;
            _events[pos].revents = defaultevent;
            LOG(DEBUG, "%d add to selece array\n", sockfd);
        }
        LOG(DEBUG, "current poll rfds list is : %s\n", RfdToString().c_str());
    }

    void ServiceIO(int pos)
    {
        char buffer[1024];
        ssize_t n = ::recv(_events[pos].fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            LOG(DEBUG, "client info# %s\n", buffer);
            std::string echo_string = "[server echo]# ";
            echo_string += buffer;
            ::send(_events[pos].fd, echo_string.c_str(), echo_string.size(), 0);
        }
        else if (n == 0)
        {
            LOG(DEBUG, "%d is closed\n", _events[pos].fd);
            ::close(_events[pos].fd);
            _events[pos].fd = defaultfd;
            _events[pos].events = _events[pos].revents = defaultevent;
            LOG(DEBUG, "current poll rfds list is : %s\n", RfdToString().c_str());
        }
        else
        {
            LOG(DEBUG, "%d recv error\n", _events[pos].fd);
            ::close(_events[pos].fd);
            _events[pos].fd = defaultfd;
            _events[pos].events = _events[pos].revents = defaultevent;
            LOG(DEBUG, "current poll rfds list is : %s\n", RfdToString().c_str());
        }
    }

    void HandlerEvent()
    {
        for (int i = 0; i < N; i++)
        {
            if (_events[i].fd == defaultfd)
                continue;
            if (_events[i].revents == POLLIN)
            {
                if (_events[i].fd == _listensock->SockFd())
                    AcceptClient();
                else
                {
                    // 普通的sockfd读事件就绪
                    ServiceIO(i);
                }
            }
        }
    }

    void Loop()
    {
        while (true)
        {
            int n = poll(_events, gnum, /*timeout*/ -1);
            switch (n)
            {
            case 0:
                LOG(INFO, "poll timeout\n");
                break;
            case -1:
                LOG(ERROR, "poll error!\n");
                break;
            default:
                LOG(DEBUG, "event happen. n: %d\n", n);
                HandlerEvent();
                break;
            }
        }
    }

    std::string RfdToString()
    {
        std::string fdstr;
        for (int i = 0; i < N; i++)
        {
            if (_events[i].fd == defaultfd)
                continue;
            fdstr += std::to_string(_events[i].fd);
            fdstr += ' ';
        }
        return fdstr;
    }

    ~PollServer() {}

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
    struct pollfd _events[gnum];
};